const qiniuUploader = require("../../utils/qiniuUploader");
const { HTTP } = require('../../utils/http');
const { api } = require('../../utils/api');
const { request } = new HTTP();

const app = getApp()
const heights = Array(...Array(81)).map((_, idx) => idx + 140);
let selectCity = {};
Page({
  data: {
    userInfo: {},
    qiniuToken: '',
    loading: false,
    optionsShow: false,
    currentAnswer: {},
    dailyIndex: null,
    wishIndex: null,
    actions: [],
    photos: [
      {src: '', index: 0},
      {src: '', index: 1},
      {src: '', index: 2},
      {src: '', index: 3},
      {src: '', index: 4},
      {src: '', index: 5}
    ],
    heightShow: false,
    heightcolumns: heights,
    cityShow: false,
    cityList: [
      {
        values: [],
        className: 'column1'
      },
      {
        values: [],
        className: 'column2',
      }
    ],
    minDate: new Date('1900-01-01').getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    currentCity: {
      index: [0, 0],
      value: ['北京', '北京']
    }
  },
  onShow() {
    this._getUserInfo();
  },
  onLoad() {
    this._getToken();
  },

  // 初始化用户图片
  _initUserPhoto() {
    this.data.userInfo.images.length > 0 && this.data.userInfo.images.forEach((item, idx) => {
      const key = `photos[${item.index}]`;
      this.setData({
        [key]: {
          src: item.image
        }
      });
    });
  },
  // 初始化地址
  _initAddress() {
    const pronviceIndex = this.data.cityList[0].values.findIndex(item => item.code == this.data.userInfo.province_id);
    const cityIndex = this.data.cityList[1].values.findIndex(item => item.code == this.data.userInfo.city_id);
    this.setData({
      'currentCity.index': [pronviceIndex, cityIndex],
      'currentCity.value': [this.data.userInfo.province, this.data.userInfo.city],
    })
    const cityPicker = this.selectComponent('.cityPicker');
	  cityPicker.setIndexes([pronviceIndex, cityIndex]);
  },
  upload(event) {
    let { id } = event.currentTarget;
    id = Number(id);
    const self = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        self.data.photos[id].src = tempFilePaths[0];
        self.setData({
          photos: self.data.photos
        });

        // 上传七牛云并入库
        self._initQiniu(tempFilePaths[0], id);
      }
    })
  },
  afterRead(event) {
    const { file, name } = event.detail;
    this.data.photos[name].src = file.url;
    this.setData({
      photos: this.data.photos
    });
  },

  addMyAnswer() {
    wx.navigateTo({url: '../myAnswer/index'});
  },

  // 问答更多操作
  answerOptions(target) {
    const { currentTarget: { dataset: { answer = {} } } } = target;
    this.setData({
      actions: [
        { name: '隐藏问答', index: 0, type: 'answer' },
        { name: '修改', index: 1, type: 'answer' }
      ],
      currentAnswer: answer,
      optionsShow: true
    });
  },
  dailyOptions(target) {
    const { currentTarget: { dataset: { index = 0 } } } = target;
    this.setData({
      actions: [
        { name: '修改', index: 0, type: 'daily' },
        { name: '删除', index: 1, type: 'daily' },
      ],
      dailyIndex: index,
      optionsShow: true
    });
  },
  wishOptions(target) {
    const { currentTarget: { dataset: { index = 0 } } } = target;
    this.setData({
      actions: [
        { name: '修改', index: 0, type: 'wish' },
        { name: '删除', index: 1, type: 'wish' },
      ],
      wishIndex: index,
      optionsShow: true
    });
  },
  onSelect(target) {
    const { detail: {index, type} } = target; 
    const actions = {
      answer: () => {
        index === 0 && this._hideAnswer(this.data.currentAnswer);
        index === 1 && this._changeAnswer(this.data.currentAnswer);
      },
      daily: () => {
        index === 0 && this._changeDailyAndWish(this.data.dailyIndex, 'daily');
        index === 1 && this._deleteDailyAndWish(this.data.dailyIndex, 'daily');
      },
      wish: () => {
        index === 0 && this._changeDailyAndWish(this.data.wishIndex, 'wish');
        index === 1 && this._deleteDailyAndWish(this.data.wishIndex, 'wish');
      }
    }
    actions[type]();
  },
  // 修改问答
  _changeAnswer(answer) {
    const url = `../editAnswer/index?id=${answer.question_id}&lastValue=${encodeURIComponent(answer.content)}&editId=${answer.id}`;
    wx.navigateTo({url});
    this.setData({optionsShow: false});
  },
  onCancle() {
    this.setData({optionsShow: false});
  },

  // 隐藏问答
  async _hideAnswer(answer) {
    const { returnCode = '' } = await request({
      url: api.userQuestionHide,
      method: 'post',
      data: {
        id: answer.id
      }
    });
    if (returnCode === '0000') {
      wx.showToast({
        title: '隐藏问答成功',
        icon: 'none',
        duration: 2000
      });
      this.setData({ optionsShow: false });
      this._getUserInfo();
    } 
  },
  addDaily() {
    wx.navigateTo({url: `../dailyAndWish/index?type=daily&manner=add`});
    this.setData({optionsShow: false});
  },
  addWish() {
    wx.navigateTo({url: `../dailyAndWish/index?type=wish&manner=add`});
    this.setData({optionsShow: false});
  },
  _changeDailyAndWish(index, type) {
    wx.navigateTo({url: `../dailyAndWish/index?index=${index}&type=${type}&manner=edit`});
    this.setData({optionsShow: false});
  },
  _deleteDailyAndWish(index, type) {
    let params = {};
    if (type === 'daily') {
      let dailys = app.globalData.userInfo.dailys;
      dailys.splice(index, 1);
      params.daily = dailys.join('|~|~');
    }
    if (type === 'wish') {
      let wishs = app.globalData.userInfo.wishs;
      wishs.splice(index, 1);
      params.wish = wishs.join('|~|~');
    }
    this._edit(params, () => {
      this.setData({ optionsShow: false });
      this._getUserInfo();
    });
  },

  // 编辑学校
  schollEdit() {
    const url = this.data.userInfo.school 
                  ? `../infoText/index?type=1&key=school&value=${encodeURIComponent(this.data.userInfo.school)}`
                  : `../infoText/index?type=1&key=school`;
    wx.navigateTo({url});
  },
  companyEdit() {
    const url = this.data.userInfo.company 
                  ? `../infoText/index?type=2&key=company&value=${encodeURIComponent(this.data.userInfo.company)}`
                  : `../infoText/index?type=2&key=company`;
    wx.navigateTo({url});
  },
  jobEdit() {
    const url = this.data.userInfo.profession 
                  ? `../infoText/index?type=3&key=profession&value=${encodeURIComponent(this.data.userInfo.profession)}`
                  : `../infoText/index?type=3&key=profession`;
    wx.navigateTo({url});
  },
  nickNameEdit() {
    const url = this.data.userInfo.nickname 
                  ? `../infoText/index?type=0&key=nickname&value=${encodeURIComponent(this.data.userInfo.nickname)}`
                  : `../infoText/index?type=0&key=nickname`;
    wx.navigateTo({url});
  },
  getLocation() {
    const url = this.data.userInfo.position
                  ? `../location/index?value=${encodeURIComponent(this.data.userInfo.position)}`
                  : '../location/index';
    wx.navigateTo({url});
  },

  // 身高关闭
  onHeightClose() {
    this.setData({heightShow: false});
  },
  heightSelect() {
    this.setData({heightShow: true});
  },
  heightConfirm(e) {
    const { value = 160 } = e.detail;
    this._edit({height: value}, () => {
      this.setData({
        heightShow: false
      });
      this._getUserInfo();
    });
  },

  // 地区
  citySelect() {
    this.setData({cityShow: true});
  },
  oncityShowClose() {
    this.setData({cityShow: false});
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    if (selectCity.code && value[0].code == selectCity.code) {
      return;
    }
    selectCity = value[0];
    this._getCitys(value[0].code, (citys) => {
      picker.setColumnValues(1, citys);
    });
  },
  cityConfirm(e) {
    const {value, index} = e.detail;
    this.setData({
      'currentCity': {
        value,
        index
      },
      cityShow: false
    });
    const params = {
      province_id: value[0].code,
      province: value[0].name,
      city_id: value[1].code,
      city: value[1].name
    };
    this._edit(params);
  },

  // 获取省份信息
  async _getProvinces() {
    const {returnCode = '', beans = []} = await request({
      url: api.getProvinces,
      method: 'get',
      data: {}
    });
    if (returnCode === '0000') {
      const key = `cityList[${0}].values`
      this.setData({
        [key]: beans
      });
      this._getCitys(this.data.userInfo.province_id || 101010000, () => {}, true);
    }
  },

  // 获取城市
  async _getCitys(provinceCode, cb, isFirst = false) {
    this.setData({ loading: true });
    const {returnCode = '', beans = []} = await request({
      url: api.getCitys,
      method: 'get',
      data: {provinceCode}
    });
    this.setData({ loading: false });
    if (returnCode === '0000') {
      const key = `cityList[${1}].values`
      this.setData({
        [key]: beans
      });
      cb && cb(beans);

      isFirst && this._initAddress();
    }
  },

  // 获取七牛上传token
  async _getToken() {
    const { returnCode = null, bean = {} } = await request({
      url: api.getQiniuToken,
      method: 'get',
      data: {}
    });
    if (returnCode === '0000') {
      this.setData({
        qiniuToken: bean.qiniuToken
      });
    }
  },

  // 初始化七牛配置
  _initQiniu(file, index) {
    const options = {
        region: 'ECN',
        uptoken: this.data.qiniuToken,
        uptokenURL: '',
        uptokenFunc: function () { },
        domain: 'https://paas.star1024.cn',
        shouldUseQiniuFileName: false
    };
    qiniuUploader.init(options);
    this.uplodQiniu(file, index);
  },

  // 上传七牛
  async uplodQiniu(filePath, index) {
    wx.showLoading({
      title: '上传中',
    })
    const self = this;
    qiniuUploader.upload(filePath, (res) => {
      const params = {
        image: res.imageURL,
        index
      };
      self._addUserImage(params);
    }, (error) => {
      wx.hideLoading();
      wx.showToast({
        title: JSON.stringify(error),
        icon: 'none',
        duration: 2000
      });
      console.error('error: ' + JSON.stringify(error));
    },
    null,
    (progress) => {
      console.log('上传进度', progress.progress);
    }, cancelTask => {
      console.log('🚀 ~ file: index.js ~ line 65 ~ uplodQiniu ~ cancelTask', cancelTask);
    });
  },
  // 将七牛云链接存入数据库
  async _addUserImage(params) {
    const { returnCode = null, bean = {} } = await request({
      url: api.addUserImage,
      method: 'post',
      data: params
    });
    wx.hideLoading();
    if (returnCode === '0000') {
      this._getUserInfo();
      wx.showToast({
        title: '照片上传成功',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 获取user 信息
  async _getUserInfo(cb) {
    const {returnCode = '', bean = {}} = await request({
      url: api.getUser,
      method: 'get',
      data: {}
    });
    if (returnCode === '0000') {
      const user = this._handleDailyAndWish(bean.user);
      app.globalData.userInfo = user;
      console.log('🚀 ~ file: index.js ~ line 367 ~ _getUserInfo ~ user', user)
      this.setData({ userInfo: user });
      this._initUserPhoto();
      this._getProvinces();
      cb && cb();
    }
  },

  // 处理日常和愿望数据
  _handleDailyAndWish(user) {
    if (user.daily) {
      const dailys = user.daily.split('|~|~');
      user.dailys = dailys;
    }
    if (user.wish) {
      const wishs = user.wish.split('|~|~');
      user.wishs = wishs;
    }
    return user;

  },

  async _edit(params, cb) {
    const {returnCode = '', bean = {}} = await request({
      url: api.editUser,
      method: 'put',
      data: params
    });
    if (returnCode === '0000') {
      wx.showToast({ title: '资料修改成功', icon: 'none', duration: 2000 });
      cb && cb();
    }
  },
  onClickLeft() {
    wx.navigateBack({
      delta: 1
    });
  },
});
